import ColumnUtils from '../utils/column-utils.js';

export default {
  data() {
    return {
      tableScroll: undefined,
      openScrollbarY: false,
      openScrollbarX: false,
      rootBody: {},
      calcColumns: [],
      tableColumnsWidth: 0
    };
  },
  computed: {
    // 这个是截取表格中的部分数据，放到了 table 组件中来显示
    calcSortData() {
      let datas = [...this.dataSource];
      // 排序
      let sortKeys = this.sortColumnsList;
      if (sortKeys.length) {
        sortKeys.forEach((col) => {
          datas = datas.sort((a, b) => {
            let aStr = a[col.dataIndex];
            let bStr = b[col.dataIndex];
            let mode = this.sortColumnsObj[col.key] === 'asc' ? 1 : -1;
            if (typeof aStr === 'number' || typeof bStr === 'number') {
              aStr = aStr || 0;
              bStr = bStr || 0;
              return (aStr - bStr) * mode;
            } else {
              aStr = aStr || '';
              bStr = bStr || '';
              return aStr.localeCompare(bStr) * mode;
            }
          });
        });
      }
      return datas;
    },
    calcOnePageCount() {
      let scrolly = 500;
      if (this.tableScroll) {
        scrolly = this.tableScroll.y;
      }
      return Math.ceil(scrolly / this.calcLineHeight);
    },
    calcDataSource() {
      let datas = [];
      if (this.calcOpenVirtuallyModel) {
        let maxStartIndex = this.startIndex + this.calcOnePageCount + this.lineScrollBufferCount;
        if (maxStartIndex > this.calcSortData.length) maxStartIndex = this.calcSortData.length;
        datas = this.calcSortData.slice(this.startIndex, maxStartIndex);
      } else {
        datas = this.calcSortData;
      }
      return datas;
    }
  },
  created() {
    this.outerClientRect = {};
    this.tableDom = {};
  },
  mounted() {
    this.initAfter();
  },
  methods: {
    initAfter() {
      // 获取当前el高宽
      let elBCR = this.$el.getBoundingClientRect();
      this.outerClientRect = elBCR;
      this.initAfterAutoColumnsWidth();
      this.initTableScroll();
      // this.initAfterScrollBarY();
    },
    initAfterAutoColumnsWidth() {
      const { calcColumns, calcRowRelection } = this;
      if (!calcColumns.length) return;
      // 加载本地存储列宽
      this.loadDragObj();
      let fullColWidth = 0;
      let autoCols = [];
      calcColumns.forEach((col) => {
        if (col.minWidth) {
          col.minWidth = ColumnUtils.getRealWidth(col.minWidth, this);
        }
        if (this.localStorageObj && this.localStorageObj[col.key]) {
          col.width = Number(this.localStorageObj[col.key]);
          col.originWidth = col.width;
        } else {
          // 适配通用列宽
          ColumnUtils.setColRealWidth(col, this);
        }
        if (col.originWidth !== 'auto') {
          fullColWidth = fullColWidth + col.width;
        } else {
          autoCols.push(col);
        }
      });
      // 加上复选列宽度
      if (calcRowRelection) {
        fullColWidth = fullColWidth + calcRowRelection.columnWidth;
      }
      if (!this.calcOpenVirtuallyModel && this.tableScroll) {
        fullColWidth = fullColWidth + this.scrollBarWidth;
      }
      this.tableColumnsWidth = fullColWidth;
      if (autoCols.length === 0) {
        // 列宽不满，最后一列填充满列宽
        if (fullColWidth < this.outerClientRect.width) {
          let normalColumns = calcColumns.filter((col) => !col.fixed);
          let lastCol = normalColumns[normalColumns.length - 1];

          let addWidth = this.outerClientRect.width - fullColWidth;
          lastCol.width = lastCol.width + addWidth;
          this.tableColumnsWidth = this.tableColumnsWidth + addWidth;
        }
      } else {
        // 优化宽度
        let otherWidth = this.outerClientRect.width - fullColWidth;
        autoCols.forEach((col) => {
          let minWidth = col.minWidth || this.minColumnWidth;
          if (otherWidth > minWidth) {
            otherWidth = otherWidth - minWidth;
            col.width = minWidth;
          } else {
            otherWidth = 0;
            col.width = minWidth;
          }
          this.tableColumnsWidth = this.tableColumnsWidth + col.width;
        });
        // 还有剩余的宽度
        if (otherWidth > 0) {
          this.tableColumnsWidth = this.tableColumnsWidth + otherWidth;
          let otherUnitWidth = otherWidth / autoCols.length;
          autoCols.forEach((col) => {
            col.width = col.width + otherUnitWidth;
          });
        }
      }
    },
    initTableScroll() {
      const {
        tableDataHeight,
        outerClientRect,
        pagination,
        paginationHeight,
        calcLineHeight,
        scrollBarWidth,
        calcOpenVirtuallyModel
      } = this;
      this.scrollHeight = outerClientRect.height;
      // 如果有翻页控件
      if (pagination) {
        this.scrollHeight = this.scrollHeight - paginationHeight;
      }
      this.scrollHeight = this.scrollHeight - calcLineHeight;
      if (!calcOpenVirtuallyModel) {
        // 出 Y 滚动条
        // 根据table比对x宽度
        // if (
        //   (tableDataHeight && tableDataHeight > this.scrollHeight) ||
        //   this.tableColumnsWidth > outerClientRect.width
        // ) {
        //   this.tableScroll = { x: outerClientRect.width - scrollBarWidth, y: this.scrollHeight };
        // } else {
        //   this.tableScroll = { x: outerClientRect.width - scrollBarWidth, y: this.scrollHeight };
        // }
        this.tableScroll = { x: outerClientRect.width - scrollBarWidth, y: this.scrollHeight };
      } else {
        this.tableScroll = { x: outerClientRect.width - scrollBarWidth, y: this.scrollHeight };
        // this.scrollHeight = this.scrollHeight - calcLineHeight;
        // 出 Y 滚动条
        if (tableDataHeight && tableDataHeight > this.scrollHeight) {
          this.openScrollbarY = true;
        } else {
          this.openScrollbarY = false;
        }
        // 根据table比对x宽度
        if (this.tableColumnsWidth > outerClientRect.width) {
          this.openScrollbarX = true;
        } else {
          this.openScrollbarX = false;
        }
      }
    },
    initAfterScrollBarY() {
      const {
        tableDataHeight,
        pagination,
        paginationHeight,
        outerClientRect,
        calcOpenVirtuallyModel,
        calcLineHeight,
        scrollBarWidth
      } = this;
      this.scrollHeight = outerClientRect.height;
      // 如果有翻页控件
      if (pagination) {
        this.scrollHeight = this.scrollHeight - paginationHeight - calcLineHeight;
      }
      // 出 Y 滚动条
      if (tableDataHeight && tableDataHeight > this.scrollHeight) {
        if (calcOpenVirtuallyModel) {
          this.openScrollbarY = true;
        } else {
          // 非虚拟滚动，必须同时出横向滚动，ant有bug
          this.tableScroll = {
            x: outerClientRect.width - scrollBarWidth,
            y: this.scrollHeight
          };
        }
      } else {
        if (calcOpenVirtuallyModel) {
          this.openScrollbarY = false;
        }
      }
      // this.tableScroll = { x: outerClientRect.width, y: outerClientRect.height };
      // 出 X 滚动条 , 需要等待table渲染完成后再判断
    },
    initAfterScrollBarX() {
      this.initTableScroll();
      return;
      // const { calcOpenVirtuallyModel, outerClientRect, scrollHeight, scrollBarWidth } = this;
      // // 根据table比对x宽度
      // if (this.tableColumnsWidth > outerClientRect.width) {
      //   if (calcOpenVirtuallyModel) {
      //     this.openScrollbarX = true;
      //   } else {
      //     // 非虚拟滚动，必须同时出横向滚动，ant有bug
      //     this.tableScroll = { x: outerClientRect.width - scrollBarWidth, y: scrollHeight };
      //   }
      // } else {
      //   if (calcOpenVirtuallyModel) {
      //     this.$refs.tableScrollX && this.$refs.tableScrollX.reset();
      //     this.openScrollbarX = false;
      //   }
      // }
      // return;
    },
    initTableDom() {
      this.tableDom.tableHeader =
        this.$refs.tableRef.$el.querySelector('.ant-table-header') ||
        this.$refs.tableRef.$el.querySelector('.ant-table-thead');

      this.tableDom.tableHeaderTable = this.tableDom.tableHeader.querySelector('table');
      this.tableDom.tableBodyBrc = this.tableDom.tableHeader.getBoundingClientRect();
      this.tableDom.tableBodyTable = this.tableDom.tableBody.querySelector('table');

      this.tableDom.tableHeaderHeight = this.tableDom.tableHeader.getBoundingClientRect().height;
      this.tableDom.tableBodyHeight = this.tableDom.tableBody.getBoundingClientRect().height;
    },
    initAfterScrollTableBody() {
      if (this.$refs.tableRef) {
        this.tableDom.tableBody = this.$refs.tableRef.$el.querySelector('.ant-table-body');
        this.tableDom.tableOuterBody =
          this.$refs.tableRef.$el.querySelectorAll('.ant-table-body-outer');
        this.mainTable =
          this.tableDom.tableBody.querySelector('.ant-table-fixed') ||
          this.tableDom.tableBody.querySelector('table');
        let tableTr = this.mainTable.querySelector('tr');
        if (tableTr) {
          this.bodyTrHeight = tableTr.getBoundingClientRect().height;
        }
        // this.table.push(this.mainTable);
        this.table = [];
        this.tableDom.tableOuterBody.forEach((child) => {
          // child.style.overflow = 'hidden';
          this.table.push(child.querySelector('.ant-table-fixed'));
          // child.querySelector('.ant-table-body-inner').style.overflow = 'hidden';
        });
      }

      if (this.tableDom.tableBody) {
        if (this.dataSource && this.dataSource.length && this.tableDom.tableBody) {
          let bodyHeight = this.scrollHeight;
          if (this.tableScroll) {
            this.tableDom.tableBody.style.height = bodyHeight + 'px';
          } else {
            bodyHeight = bodyHeight + this.calcLineHeight;
            this.tableDom.tableBody.style.height = bodyHeight + 'px';
          }
          this.tableDom.tableOuterBody.forEach((child) => {
            child.querySelector('.ant-table-body-inner').style.height = bodyHeight + 'px';
          });
        } else {
          this.tableDom.tableBody.style.height = 0 + 'px';
          this.tableDom.tableOuterBody.forEach((child) => {
            child.querySelector('.ant-table-body-inner').style.height = 0 + 'px';
          });
        }
      }
    },
    initAfterTableHandel() {
      // console.log('updated:---->: calcSortData 3');
      // console.time(`updated:-------scoll3`);
      this.table = [];
      if (!this.$refs.tableRef) {
        return;
      }
      // 暂存各种table dom brc
      this.tableDom = {};
      this.tableDom.tableBody = this.$refs.tableRef.$el.querySelector('.ant-table-body');
      this.tableDom.tableOuterBody =
        this.$refs.tableRef.$el.querySelectorAll('.ant-table-body-outer');

      this.initTableDom();
      this.initAfterScrollBarX();

      this.$nextTick(() => {
        this.initAfterEmptyHeight();
        this.initAfterScrollTableBody();
      });
    },
    initAfterEmptyHeight() {
      let emptyDom = this.$el.querySelector('.ant-table-placeholder');
      if (emptyDom) {
        emptyDom.style.height = this.scrollHeight + 'px';
      }
    },
    updateTableColumnWidth(col, changeAfterWidth, colIndex) {
      let cutWidth = col.width - changeAfterWidth;
      let tableColumnsWidth = this.tableColumnsWidth - cutWidth;
      if (changeAfterWidth >= col.width) {
        col.width = changeAfterWidth;
        this.tableColumnsWidth = tableColumnsWidth;
      } else {
        if (tableColumnsWidth >= this.outerClientRect.width) {
          col.width = changeAfterWidth;
          this.tableColumnsWidth = tableColumnsWidth;
        } else {
          let { leftColumns, normalColumns } = this;
          // 只能补偿非右侧冻结列
          let columns = [...leftColumns, ...normalColumns];
          let adjacentCol = null;
          if (columns.length - 1 > colIndex) {
            adjacentCol = columns[colIndex + 1];
          } else {
            adjacentCol = columns[colIndex - 1];
          }
          // 多余的宽度要分配给其它列，这里暂时分配给相邻列
          // 如果只有一列，则不允许设置宽度。
          if (adjacentCol) {
            col.width = changeAfterWidth;
            adjacentCol.width = adjacentCol.width + cutWidth;
            // this.draggingState[adjacentCol.key] = adjacentCol.width;
            adjacentCol.draggingWidth = adjacentCol.width;
          }
        }
      }
    }
  }
};
